package thu.sorit.net;

import java.io.IOException;
import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Handler;

public class Downloader {
    
    public static final int MSG_OK = 1;
    
    public static final int MSG_FAIL = 2;

    private static final int INIT_BUF_SIZE = 65536;
    
    private static final long MAX_TEST_NANO = 2000000000;
    
    private static final int MAX_TEST_SIZE = 5000000;
    
    private static byte buffer[] = new byte[INIT_BUF_SIZE];
    
    public static double testSpeed(String addr) {
        try {
        	HttpURLConnection connection;
            URL url = new URL(addr);
            while (true) {
            	connection = (HttpURLConnection) url.openConnection();
            	connection.setInstanceFollowRedirects(false);
            	connection.setRequestProperty("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11");
            	connection.connect();
            	if (connection.getResponseCode() == 302) {
            		url = new URL(connection.getHeaderField("Location"));
            		connection.disconnect();
            	} else {
            		break;
            	}
            }
            InputStream input = connection.getInputStream();
            long testTime = 0;
            int sum = 0;
            while (sum < MAX_TEST_SIZE && testTime < MAX_TEST_NANO) {
            	long s = System.nanoTime();
            	int count = input.read(buffer, 0, INIT_BUF_SIZE);
            	testTime += System.nanoTime() - s;
            	if (count == -1) {
            		break;
            	} else {
            		sum += count;
            	}
            }
            input.close();
            connection.disconnect();
            return (double) sum * 1000000000 / testTime;
        } catch (IOException e) {
        	e.printStackTrace();
        	return Double.NaN;
        }
    }
    
}

